import re
from django import http
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.views import View
from pymysql import DatabaseError
from carts.utils import merge_cart_cookie_to_redis
from meiduo_mall.utils.response_code import RETCODE
from users.models import User


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 接收参数
        user_name = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        cpwd = request.POST.get('cpwd')
        phone = request.POST.get('phone')
        allow = request.POST.get('allow')
        # 判断参数是否齐全
        if not all([user_name, pwd, cpwd, phone]):
            return http.HttpResponseForbidden('参数不全')
        # 判断用户名是否是5-20个字符，重复
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', user_name):
            return http.HttpResponseForbidden('用户名格式错误')
        if User.objects.filter(username=user_name):
            return http.HttpResponseForbidden('用户名已注册')
        # 判断密码是否是8-20个数字
        if not re.match(r'[0-9]{8,20}$', pwd):
            return http.HttpResponseForbidden('密码格式错误')
        # 判断两次密码是否一致
        if pwd != cpwd:
            return http.HttpResponseForbidden('密码不一致')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('未同意用户协议')
        # 手机号
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return http.HttpResponseForbidden('手机号格式')
        if User.objects.filter(mobile=phone):
            return http.HttpResponseForbidden('用户名已注册')
        # 保存注册数据
        try:
            user = User.objects.create_user(username=user_name, password=pwd, mobile=phone)
            login(request, user)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})
        response = redirect('/')

        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        response = merge_cart_cookie_to_redis(request, response)

        # 响应注册结果
        return response


class UserNameView(View):
    def get(self, request, username):
        count =User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileView(View):
    def get(self, request, mobile):
        count =User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        remembered = request.POST.get('remembered')
        # 验证
        if not all([username, password]):
            return http.HttpResponseForbidden('参数不全')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('用户名格式错误')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码格式错误')
        # 处理
        # user = User.objects.fitler(username = username)
        # 重写认证方法
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        login(request, user)
        if remembered != 'no':
            request.session.set_expiry(0)
        else:
            # 记住用户：None表示两周后过期
            request.session.set_expiry(None)
        response = redirect('/')

        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        response = merge_cart_cookie_to_redis(request, response)
        return response


class UserInfo(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        context = {
            'username': user.username,
            'mobile': user.mobile,
        }
        return render(request, 'user_center_info.html', context)


class LogoutView(View):
    # 退出登录
    def get(self,request):
        #清除ｓｅｓｓｉｏｎ
        logout(request)
        response = redirect('/')
        response.delete_cookie('username')
        return response


class EmailsView(View):
    pass


